﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace Agr.CQRS.Infrastructure.ServiceBus
{
    public class ServiceBus : IServiceBus
    {
        private Dictionary<Type, IList> handlers = new Dictionary<Type, IList>();

        public void Subscribe<T>(ServiceBusEventHandler<T> eventHandler)
        {
            getHandlerListFor(typeof(T)).Add(eventHandler);
        }

        private IList getHandlerListFor(Type t)
        {
            if (!handlers.ContainsKey(t))
                handlers.Add(t, new ArrayList());

            return handlers[t];
        }

        private IEnumerable<ServiceBusEventHandler<T>> getCallableHandlersFor<T>()
        {
            return
                from object h in getHandlerListFor(typeof(T))
                select (ServiceBusEventHandler<T>)h;
        }

        public void Publish<T>(T ev)
        {
            getCallableHandlersFor<T>().ToList().ForEach(x => x.BeginInvoke(ev, null, null));
        }

    }


}
